package com.chat.chatroom.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * 线程池配置
 */
@Configuration
@RefreshScope
public class ThreadPoolConfig {

    @Value("${async.executor.thread.corePoolSize:5}")
    private int corePoolSize;

    @Value("${async.executor.thread.maximumPoolSize:20}")
    private int maximumPoolSize;

    private static ThreadPoolExecutor executor;

    @Bean("executor")
    public Executor initProcessorThreadPool() {
        return executor = new ThreadPoolExecutor(
                corePoolSize
                , maximumPoolSize
                , 60
                , TimeUnit.SECONDS
                , new SynchronousQueue<>(true) //公平策略,FIFO
                , new BlockRejectedExecutionHandler()
        );
    }

    public static <T> Future<T> submit(Callable<T> task) {
        return executor.submit(task);
    }

    public static void submit(Runnable runnable) {
        executor.submit(runnable);
    }

    private static class BlockRejectedExecutionHandler implements RejectedExecutionHandler {

        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
            try {
                executor.getQueue().put(r);
            } catch (InterruptedException ignored) {
            }
        }
    }
}
